package com.mstore.action;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.mstore.config.Constants;
import com.mstore.pojo.Account;
import com.mstore.pojo.BWeixinurl;
import com.mstore.pojo.Reply;
import com.mstore.pojo.WeiXinMenu;
import com.mstore.service.BWeixinurlService;
import com.mstore.service.ReplyService;
import com.mstore.service.ThirdActService;
import com.mstore.service.WeiXinMenuService;
import com.opensymphony.xwork2.ActionContext;
/**
 * 
 * 
 *	微信菜单
 */
public class WeiXinMenuAction extends BaseAction {
	
	private static final long serialVersionUID = -5326399984911434895L;
	
	private WeiXinMenuService weiXinMenuService;
	private ReplyService replyService;
	private ThirdActService thirdactService;
	private BWeixinurlService bWeixinurlService;

	private WeiXinMenu weiXinMenu;

	private List<WeiXinMenu> menus = new ArrayList<WeiXinMenu>();
	private List<WeiXinMenu> menus1;
	private List<WeiXinMenu> menus2;
	private List<WeiXinMenu> menus3;

	private List<Reply> replies;
	
	private List<BWeixinurl> bWeixinurls;

	private Map<String,Object> session = ActionContext.getContext().getSession();

	private String result;
	
	private Long menuCount;
	
	private static Logger logger = Logger.getLogger(WeiXinMenuAction.class
			.getName()); 

	/**
	 * 跳转到添加菜单页面
	 * @return
	 */
	public String initWeiXinMenu() {
		Account account = (Account) session.get("account");
		if (account == null) {
			result = "系统异常，请重新登陆！";
			return "error";
		}
		
		Long eaId = account.getId();
		
		weiXinMenu = new WeiXinMenu();
		weiXinMenu.setEaId(eaId);
		List<WeiXinMenu> menusList = weiXinMenuService.getWeiXinMenuByEaId(weiXinMenu);
		
		if (menusList.size() > 0) {
			menus.add(menusList.get(0));
			
			int index = 1;
			for (int i = 1; i < 18; i++) {
				if (index == menusList.size()) {
					if (index < 18) { // 补足空位
						for (int j = index; j < 18; j++) {
							WeiXinMenu menu = new WeiXinMenu();
							menu.setType("click");
							menus.add(menu);
						}
					}else {
						break;
					}
					break;
				}
				WeiXinMenu xinMenu = menusList.get(index);
				if (xinMenu.getParentId() == 0) {
					if (i == 6 || i == 12) {
						menus.add(xinMenu);
						index++;
					}else {
						WeiXinMenu menu = new WeiXinMenu();
						menu.setType("click");
						menus.add(menu);
					}
				}else {
					menus.add(xinMenu);
					index++;
				}
			}
			
			for (WeiXinMenu menu : menus) {
				if ("view".equals(menu.getType())) {
					BWeixinurl weixinurl = new BWeixinurl();
//					String url = menu.getUrl();
					//url%3D
//					int idx = url.indexOf("url%3D");
//					String urlKey = url.substring(idx + 6, idx + 7);
//					weixinurl.setId(Long.parseLong(urlKey));
//					weixinurl = bWeixinurlService.getWeixinurlById(weixinurl);
					
					String key = menu.getKey();
					weixinurl.setId(Long.parseLong(key));
					weixinurl = bWeixinurlService.getWeixinurlById(weixinurl);
					menu.setWeixinurl(weixinurl);
				}
			}
		}
		
		menuCount = weiXinMenuService.getWeiXinMenuCount(weiXinMenu);
		
		Reply reply = new Reply();
		reply.setEaId(eaId);
		replies = replyService.watchMenuReply(reply);

		bWeixinurls = bWeixinurlService.getWeixinMenuUrlByEaId(eaId);
		
		return "toWeiXinMenu";
	}
	
	public String addWeiXinMenu() {
		
		/**
		 * 菜单存储策略：
		 * 顺序循环menus，第一个对象是【主菜单1】，如果【主菜单1】验证不通过，退出循环。判定菜单不合法。如果验证通过，继续循环。
		 * 第二个对象是【子菜单1】，如果验证不通过，退出循环。判定菜单不合法。如果验证通过，表示菜单是合法的，可以存储菜单。
		 * 如果任一子菜单验证不通过，则其后的子菜单不再判断，直接退出循环。
		 */

		Account account = (Account) session.get("account");
		if (account == null) {
			result = "系统异常，请重新登陆！";
			return "error";
		}
		
		if (!verifyMainMenu(menus.get(0))) {
			result = "3"; // 代表主菜单1没有填写
			return "addSuccess";
		}

		if (menuCount != 0) {
			// 删除原菜单
			weiXinMenu = new WeiXinMenu();
			weiXinMenu.setEaId(account.getId());
			weiXinMenuService.delMenu(weiXinMenu);
		}
		
		List<WeiXinMenu> menus1 = new ArrayList<WeiXinMenu>();
		List<WeiXinMenu> menus2 = new ArrayList<WeiXinMenu>();
		List<WeiXinMenu> menus3 = new ArrayList<WeiXinMenu>();
		
		boolean menu0 = true; // 标示主菜单1是否为空,true:不为空，false:空

		for (int i = 0; i < menus.size(); i++) {
			if (0 <= i && i < 6) {
				if (i == 0) {
					if (!verifyMainMenu(menus.get(0))) {
						menu0 = false;
						break;
					}
				}
				if (i == 1) {
					if (!verifyMenu(menus.get(1))) {
						break;
					}
				}

				if (i > 1) {
					if (!verifyMenu(menus.get(i))) {
						i = 5;
						continue;
					}
				}
				menus1.add(menus.get(i));
			} else if (6 <= i && i < 12) {
				if (i == 6) {
					if (!verifyMainMenu(menus.get(6))) {
						break;
					}
				}
				if (i == 7) {
					if (!verifyMenu(menus.get(7))) {
						break;
					}
				}

				if (i > 7) {
					if (!verifyMenu(menus.get(i))) {
						i = 11;
						continue;
					}
				}
				menus2.add(menus.get(i));
			} else {
				if (i == 12) {
					if (!verifyMainMenu(menus.get(12))) {
						break;
					}
				}
				if (i == 13) {
					if (!verifyMenu(menus.get(13))) {
						break;
					}
				}

				if (i > 13) {
					if (!verifyMenu(menus.get(i))) {
						break;
					}
				}
				menus3.add(menus.get(i));
			}
		}

		if (menus1.size() >= 2) {
			addMenus(menus1, account);
		}
		if (menus2.size() >= 2) {
			addMenus(menus2, account);
		}
		if (menus3.size() >= 2) {
			addMenus(menus3, account);
		}
		
		if (!menu0) {
			result = "3"; // 代表主菜单1没有填写
			return "addSuccess";
		}
		
		result = "1"; // 代表“菜单已保存”

		return "addSuccess";
	}
	/**
	 * 推送微信菜单
	 * @return
	 */
	public String publishWeiXinMenu(){
		try {
			Object object = session.get("account");
			if (object == null) {
				result = ERROR_TIP;
				return "error";
			}
			Account account = (Account)object;
			
			String responseStr = executeHttpClient(account);
			
			if (responseStr.contains("error")) {
				result = "菜单创建失败！" + responseStr;
			}else if("ok".equals(responseStr)){
				result = "2"; // 代表“菜单创建成功”
			}
			
			return "addSuccess";
		}
		catch (Exception e) {
			logger.error("推送微信菜单报错", e);
		}
		return "error";
	}

	private boolean verifyMainMenu(WeiXinMenu menu) {
		if (verifyNullString(menu.getName())) {
			return false;
		}
		return true;
	}

	private boolean verifyMenu(WeiXinMenu menu) {
		if (verifyNullString(menu.getName())) {
			return false;
		}
		if ("click".equals(menu.getType())) {
			if (verifyNullString(menu.getKey())) {
				return false;
			}
		} else if ("view".equals(menu.getType())) {
			if (verifyNullString(menu.getUrl())) {
				return false;
			}
		}
		return true;
	}

	private boolean verifyNullString(String str) {
		if (str == null || "".equals(str.trim())) {
			return true;
		}
		return false;
	}

	/**
	 * 添加菜单
	 */
	private void addMenus(List<WeiXinMenu> menus, Account account) {
		String createTime = getCreateTime();
		Long ea_id = account.getId();
		for (int i = 0; i < menus.size(); i++) {
			if (i == 0) {
				menus.get(0).setCreateTime(createTime);
				menus.get(0).setEaId(ea_id);
				menus.get(0).setParentId(0L);
				weiXinMenuService.saveMenu(menus.get(0));
				continue;
			}
			if ("view".equals(menus.get(i).getType())) {
				String urlId = menus.get(i).getUrl();
//				ThirdAct thirdAct = new ThirdAct();
//				thirdAct.setEaId(ea_id);
//				thirdAct = thirdactService.getThirdActByEaId(thirdAct);
//
//				if (thirdAct == null) {
//					continue;
//				}
//
				BWeixinurl bWeixinurl = new BWeixinurl();
				bWeixinurl.setId(Long.parseLong(urlId));
				bWeixinurl = bWeixinurlService.getWeixinurlById(bWeixinurl);
				if (bWeixinurl == null) {
					continue;
				}
				String url = bWeixinurl.getUrl();
				if (StringUtils.isBlank(url)) {
					continue;
				}
				// 生成url
//				String url = WeixinUtils.getWeixinUrl(thirdAct, bWeixinurl);
				menus.get(i).setUrl(url);
				menus.get(i).setKey(bWeixinurl.getId().toString());
			}
			menus.get(i).setCreateTime(createTime);
			menus.get(i).setEaId(ea_id);
			menus.get(i).setParentId(menus.get(0).getId());
			menus.get(i).setSort(i);
			weiXinMenuService.saveMenu(menus.get(i));
		}

	}

	private String executeHttpClient(Account account) {
		// 构造HttpClient的实例
		HttpClient httpClient = new HttpClient();
		// 创建GET方法的实例 http://www.wimi.me/gateway/menu/create
//		GetMethod getMethod = new GetMethod("http://crm.wumi.me/gateway/menu/create");
		GetMethod getMethod = new GetMethod(Constants.createMenuUrl);
		
		// 使用系统提供的默认的恢复策略
		getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
				new DefaultHttpMethodRetryHandler());
		// 设置参数(eaId)
		getMethod.setQueryString("eaId=" + account.getId());

		String responseStr = null;
				
		try {
			// 执行getMethod
			int statusCode = httpClient.executeMethod(getMethod);
			if (statusCode != HttpStatus.SC_OK) {
				System.err.println("Method failed: "
						+ getMethod.getStatusLine());
			}
			// 读取内容
			byte[] responseBody = getMethod.getResponseBody();
			// 处理内容
			System.out.println(new String(responseBody));
			responseStr = new String(responseBody);
		} catch (HttpException e) {
			// 发生致命的异常，可能是协议不对或者返回的内容有问题
			System.out.println("Please check your provided http address!");
			e.printStackTrace();
		} catch (IOException e) {
			// 发生网络异常
			e.printStackTrace();
		} finally {
			// 释放连接
			getMethod.releaseConnection();
			
		}
		
		return responseStr;
	}

	/**
	 * URL编码（utf-8）
	 * 
	 * @param source
	 * @return
	 */
	public static String urlEncodeUTF8(String source) {
		String result = source;
		try {
			result = java.net.URLEncoder.encode(source, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		return result;
	}
	
	public WeiXinMenuService getWeiXinMenuService() {
		return weiXinMenuService;
	}

	public void setWeiXinMenuService(WeiXinMenuService weiXinMenuService) {
		this.weiXinMenuService = weiXinMenuService;
	}

	public WeiXinMenu getWeiXinMenu() {
		return weiXinMenu;
	}

	public void setWeiXinMenu(WeiXinMenu weiXinMenu) {
		this.weiXinMenu = weiXinMenu;
	}

	public List<WeiXinMenu> getMenus() {
		return menus;
	}

	public void setMenus(List<WeiXinMenu> menus) {
		this.menus = menus;
	}

	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}

	public List<Reply> getReplies() {
		return replies;
	}

	public void setReplies(List<Reply> replies) {
		this.replies = replies;
	}

	public ReplyService getReplyService() {
		return replyService;
	}

	public void setReplyService(ReplyService replyService) {
		this.replyService = replyService;
	}

	public ThirdActService getThirdactService() {
		return thirdactService;
	}

	public void setThirdactService(ThirdActService thirdactService) {
		this.thirdactService = thirdactService;
	}

	public BWeixinurlService getbWeixinurlService() {
		return bWeixinurlService;
	}

	public void setbWeixinurlService(BWeixinurlService bWeixinurlService) {
		this.bWeixinurlService = bWeixinurlService;
	}

	public List<BWeixinurl> getbWeixinurls() {
		return bWeixinurls;
	}

	public void setbWeixinurls(List<BWeixinurl> bWeixinurls) {
		this.bWeixinurls = bWeixinurls;
	}

	public Long getMenuCount() {
		return menuCount;
	}

	public void setMenuCount(Long menuCount) {
		this.menuCount = menuCount;
	}

	public List<WeiXinMenu> getMenus1() {
		return menus1;
	}

	public void setMenus1(List<WeiXinMenu> menus1) {
		this.menus1 = menus1;
	}

	public List<WeiXinMenu> getMenus2() {
		return menus2;
	}

	public void setMenus2(List<WeiXinMenu> menus2) {
		this.menus2 = menus2;
	}

	public List<WeiXinMenu> getMenus3() {
		return menus3;
	}

	public void setMenus3(List<WeiXinMenu> menus3) {
		this.menus3 = menus3;
	}

}
